package com.kylin.upms.biz.common.aop;
import com.alibaba.fastjson.JSON;
import com.kylin.upms.biz.annotation.Log;
import com.kylin.common.log.entity.AopLogEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class AopConfig {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.kylin.upms.biz.web.*.*(..))")
    public void poincut(){
    }

    @Autowired
    KafkaTemplate<Object,String> kafkaTemplate;

    @AfterReturning(pointcut="poincut()")
    public void after(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer stringBuffer = new StringBuffer("请求信息为>>>>>>:");
        AopLogEntity aopLogEntity = new AopLogEntity();
        aopLogEntity.setUrl(request.getRequestURI());
        aopLogEntity.setIp(request.getRemoteAddr());
        aopLogEntity.setMethod(request.getMethod());
        aopLogEntity.setServerName(request.getServerName());
        aopLogEntity.setPort(String.valueOf(request.getServerPort()));
        aopLogEntity.setArgs(joinPoint.getArgs());
        aopLogEntity.setClassName(joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Log annotation = method.getAnnotation(Log.class);
        if (annotation!=null){
            stringBuffer.append(annotation.value()+":");
        }
        logger.info(stringBuffer.append(JSON.toJSONString(aopLogEntity)).toString());
        kafkaTemplate.send("kylinLog",JSON.toJSONString(aopLogEntity));
    }
}
